//
//  CCYHomeViewController.swift
//  03.微博
//
//  Created by 蔡承毅 on 16/9/16.
//  Copyright © 2016年 IOS. All rights reserved.
//

import UIKit
import SVProgressHUD

class CCYHomeViewController: CCYBaseViewController {
    
    var statusVMs: [CCYStatusVM]? {
        didSet{
            tableview.reloadData()
        }
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        tableview.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        tableview.register(UINib(nibName: "CCYStatusCell", bundle: nil), forCellReuseIdentifier: "cell")
        // 预估行高
        tableview.estimatedRowHeight = 200
        // 行高根据cell的约束自动计算
        tableview.rowHeight = UITableViewAutomaticDimension
        // 去掉cell分割线
        tableview.separatorStyle = UITableViewCellSeparatorStyle.none
        setupNavigationBar()
        CCYStatusListVM.shared.loadStatus { (statusVMs: [CCYStatusVM]?,error: Error?) in
            
            if error != nil{
                print("获取微博数据失败 = \(error)")
                SVProgressHUD.show(withStatus: "获取微博数据失败")
                return
            }
            
            self.statusVMs = statusVMs
        }
    }
    func setupNavigationBar() -> Void {
        let name = CCYUserAccountVM.shared.userAccount?.screen_name
        
        let bottom = CCYHomeTitleButton(name: name)
        bottom.addTarget(self, action: #selector(titleButtonClick(button:)), for: .touchUpInside)
        
        self.navigationItem.titleView = bottom
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(name: "navigationbar_friendsearch")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(name: "navigationbar_pop")
        
        
    }
    
    func titleButtonClick(button:UIButton) -> Void {
        button.isSelected = !button.isSelected
        
        let transform = button.isSelected ? CGAffineTransform(rotationAngle: CGFloat(M_PI - 0.001)) : CGAffineTransform.identity
        UIView.animate(withDuration: 0.25) { 
            button.imageView?.transform = transform
        }
        
    }
}

extension CCYHomeViewController{
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.statusVMs?.count ?? 0
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableview.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CCYStatusCell
        
        let statusVM = self.statusVMs?[indexPath.row]
//        cell.textLabel?.text = statusVM?.status.text
        cell.statusVM = statusVM
        
        return cell
    }
}

